package com.study.jyg.rxjava2study.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.study.jyg.rxjava2study.R;

public class BarGraphItem extends View {

    private static final String TAG = "BarGraphView";
    private Paint paint;
    private int measuredWidth;
    private int measuredHeight;
    private double ratio;
    private GradientDrawable gradientDrawable;

    public BarGraphItem(Context context) {
        super(context);
        initPaint();
    }

    public BarGraphItem(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    public BarGraphItem(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
    }

    //设置柱子的高度
    public void setRatio(double ratio) {
        this.ratio = ratio;
        invalidate();
    }

    private void initPaint() {
        paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(getResources().getColor(R.color.black));
        paint.setAntiAlias(true);

        int colors[] = {getResources().getColor(R.color.colorRed), getResources().getColor(R.color.colorAccent)};
        gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP,colors);
        //设置渐变色
        gradientDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
        //设置顶部圆角
        gradientDrawable.setCornerRadii(new float[]{15,15,15,15,0,0,0,0});
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measuredWidth = getMeasuredWidth();
        measuredHeight = getMeasuredHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //画柱子的背景色
        canvas.drawRect(0, 0, measuredWidth, measuredHeight, paint);
        //计算柱子实际高度
        if (ratio != 0){
            int ratioHeight = (int) (measuredHeight * ratio + 0.5);
            //默认坐标原点在左上角，这里我们把画布移到左上角
            canvas.translate(0,measuredHeight - ratioHeight);
            //x,y,w,h
            gradientDrawable.setBounds(0,0,measuredWidth, ratioHeight);
            gradientDrawable.draw(canvas);
        }
    }
}
